Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Here's how it can implement bubble sort in C++:
#include <iostream>
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
std::swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(arr) / sizeof(arr[0]);
std::cout << "Original array: ";
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
bubbleSort(arr, size);
std::cout << "\nSorted array: ";
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
When run this code, it will sort the arr array in ascending order using bubble sort and print both the original and sorted arrays. Here's a Sample Output:
Original array: 64 34 25 12 22 11 90
Sorted array: 11 12 22 25 34 64 90
As it can see, the array is sorted in ascending order after applying the bubble sort algorithm.
question
question2